//
//  YRMainTabBar.swift
//  新浪微博
//
//  Created by Viper on 16/6/24.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit

//声明协议
protocol YRTabBarDelegate : NSObjectProtocol{
    
    //声明协议方法
    func composeButtonClick()
    
}

class YRMainTabBar: UITabBar {

    //声明代理
    //使用weak修饰代理 需要集成NSObjectProtocol基协议
    weak var YRDelegate: YRTabBarDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupUI(){
        
        addSubview(composeBtn)
    }
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //UITabBarButton的宽度
        let width = SCREENW / 5
        
        //记录表示
        var index : CGFloat = 0
        
        //遍历得到UITabBarButton
        for value in self.subviews{
            //判断其是UITabBarButton 因为UITabBarButton是真是存在的 不会为nil
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
               
                value.frame.size.width = width
                
                //设置X轴
                value.frame.origin.x = index * width
                
                index++
                
                if index == 2 {
                    index++
                }
            }
            
        }
        

        composeBtn.center.x = self.frame.width * 0.5
        
        composeBtn.center.y = self.frame.height * 0.5
        
        
    }
   
   private lazy var composeBtn : UIButton = {
        
        let button = UIButton()
    
        button.addTarget(self, action: #selector(YRMainTabBar.buttonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.sizeToFit()
        
        return button
        
    }()
    
    //监听方法 (如果私有后 需要加@objc  防止程序找不到该方法)
   @objc private func buttonClick(){
    
    YRDelegate?.composeButtonClick()
        
    }
    
    
}



